package com.gcloud.mesh.framework.core.util;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonUtil {

	/**
	 * List<T> 转 json 保存到数据库
	 */
	public static <T> String listToJson(List<T> ts) {
		String jsons = JSON.toJSONString(ts);
		return jsons;
	}

	/**
	 * json 转 List<T>
	 */
	public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
		@SuppressWarnings("unchecked")
		List<T> ts = (List<T>) JSONArray.parseArray(jsonString, clazz);
		return ts;
	}
	
	public static <T>  T jsonToObject(String jsonString, Class<T> clazz) {
		return JSONObject.parseObject(jsonString, clazz);
	}

	/*
	 * @Desccription 把对象转成JsonObject
	 * 
	 * @Date 2018/2/21
	 * 
	 * @Created by yaowj
	 * 
	 * @Param obj
	 * 
	 * @Return com.alibaba.fastjson.JSONObject
	 */
	public static JSONObject toJSONObject(Object obj) {

		JSONObject result = null;
		if (obj != null) {
			String jsonStr = JSON.toJSONString(obj);
			result = JSONObject.parseObject(jsonStr);

		}
		return result;
	}

	/*
	 * @Desccription 把JSON对象转成指定对象
	 * 
	 * @Date 2018/2/21
	 * 
	 * @Created by yaowj
	 * 
	 * @Param obj
	 * 
	 * @Return com.alibaba.fastjson.JSONObject
	 */
	public static <T> T toJSONObject(Object obj, Class<T> clazz) {
		T result = null;
		if (obj != null) {
			String jsonStr = JSON.toJSONString(obj);
			result = JSONObject.parseObject(jsonStr, clazz);
		}
		return result;
	}

	public static TreeMap<String, Object> jsonToTreeMap(String strJson) {
		Map<String, Object> res = JSONObject.parseObject(strJson);
		return new TreeMap<String, Object>(res);
	}
	
	
	public static <D> D jsonObjectToObject(JSONObject jsonObject, Class<D> d) {
		return JSONObject.parseObject(jsonObject.toJSONString(), d);
	}
	
	public  static String sortConfigMap(String config) {
		if (StringUtils.isNotBlank(config)) {
			TreeMap<String, Object> treeMap = JsonUtil.jsonToTreeMap(config);
			return JSONObject.toJSON(treeMap).toString();
		} else {
			return null;
		}
	}
}
